import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper/api/mohu.dart';
import 'package:wallpaper/components/video/video_list.dart';
import 'package:wallpaper/model/random_video_base.dart';

class VideoListPage extends StatefulWidget {
  final String type;
  const VideoListPage({super.key, required this.type});

  @override
  State<VideoListPage> createState() => _VideoPageState();
}

class _VideoPageState extends State<VideoListPage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  int limit = 30;
  int page = 1;
  final List<VideoBaseInfo> videos = [];
  bool isLoading = false;
  Future<void> getVideoWallpaper() async {
    setState(() {
      isLoading = true;
    });
    if (!mounted) return;
    try {
      Response res;
      if (widget.type == 'pc') {
        res = await getDuBaVideoWallpaperPC(limit: limit, page: page);
      } else {
        res = await getDuBaVideoWallpaper(limit: limit, page: page);
      }
      if (res.data['code'] == 200) {
        List datas = res.data['data'];
        for (var i = 0; i < datas.length; i++) {
          VideoBaseInfo video = VideoBaseInfo(
            cover: datas[i]['phone_img_url'],
            height: 1920,
            width: 1080,
            url: datas[i]['video_url'],
            tag: datas[i]['decs'].replaceAll(',', ' '),
          );
          setState(() {
            videos.add(video);
          });
        }
      }
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    getVideoWallpaper();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return VideoList(
        videoList: videos,
        isLoading: isLoading,
        isPC: widget.type == 'pc',
        onImageBottomLoading: () {
          if (isLoading) return;
          page++;
          getVideoWallpaper();
        },
        onImageListRefresh: () {
          setState(() {
            page = 1;
            videos.clear();
          });
          getVideoWallpaper();
        });
  }

  @override
  bool get wantKeepAlive => true;
}
